import 'dart:async';
import 'dart:io';

import 'package:bruno/bruno.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/network_image_load/image_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/alarm_util.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/navigate_utils.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import '../../../components/log_utils.dart';
import 'device_list_model.dart';

class DeviceWidget extends StatefulWidget {
  final DeviceListModel model;

  /// 是否实时刷新在线状态
  final bool isRealTime;

  final void Function(DeviceListModel)? onItemTaped;

  final EdgeInsets? margin;

  final double borderRadius;

  ///设备名称的样式
  final TextStyle? titleStyle;

  const DeviceWidget(this.model,
      {this.onItemTaped,
      this.isRealTime = false,
      this.margin = const EdgeInsets.fromLTRB(16, 10, 16, 0),
      this.borderRadius = 8,
      this.titleStyle,
      super.key});

  @override
  State<DeviceWidget> createState() => _DeviceWidgetState();
}

class _DeviceWidgetState extends State<DeviceWidget> {
  /// 订阅数据流类
  UseSubsribe useSubsribe = UseSubsribe();

  ///
  StreamSubscription<Map<String, dynamic>>? streamSubscription;

  ///
  ConnectStatusType? connectStatus;

  @override
  void initState() {
    connectStatus = widget.model.connectStatus;
    if (widget.isRealTime) {
      subscribeConnectStatus();
    }

    super.initState();
  }

  @override
  void didUpdateWidget(covariant DeviceWidget oldWidget) {
    if (widget.model != oldWidget.model) {
      connectStatus = widget.model.connectStatus;
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() async {
    disposeSubscribeConnectStatus();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        child: Container(
          padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),
          margin: widget.margin,
          decoration: BoxDecoration(
              color: Colour.white,
              borderRadius: BorderRadius.circular(widget.borderRadius)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 53,
                child: Row(
                  children: [
                    Expanded(
                      child: Text.rich(
                        TextSpan(
                            text: (widget.model.deviceName ??
                                widget.model.name ??
                                ''),
                            children: [
                              if (widget.model.masterSlaveMode != null)
                                TextSpan(
                                    text:
                                        '（${widget.model.masterSlaveMode!.label}）')
                            ]),
                        style: widget.titleStyle ?? TextStyles.f18.mediumStyle,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    if (widget.model.connectStatus != null)
                      Padding(
                        padding: EdgeInsets.only(left: 10.w),
                        child: statusWidget(connectStatus),
                      ),
                  ],
                ),
              ),
              // 主从系统名称
              // if (widget.model.groupName != null)
              //   Padding(
              //     padding: const EdgeInsets.only(bottom: 12),
              //     child: BrnTagCustom(
              //       tagText: widget.model.groupName!,
              //       fontSize: 12.sp,
              //       textPadding:
              //           EdgeInsets.symmetric(horizontal: 4.w, vertical: 2),
              //       backgroundColor: const Color(0x1A0984F9),
              //       textColor: Colour.primaryColor,
              //     ),
              //   ),
              ...widget.model.infos.map(
                (e) => Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: 105.w,
                        child: Text(e.label, style: TextStyles.lf14),
                      ),
                      Expanded(
                        child: Text(
                          e.value,
                          maxLines: 2,
                          style: e.valueTextStyle ??
                              TextStyle(
                                color: Colour.mainTextColor,
                                fontSize: 14.sp,
                              ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      )
                    ],
                  ),
                ),
              ),
              const SizedBox(
                height: 16,
              ),
              nextDeviceWidget()
            ],
          ),
        ),
        onTap: () {
          if (widget.onItemTaped != null) {
            AlarmUtil.fromModule = AlarmFromWhereType.device.value;
            if (widget.model != null) {
              widget.onItemTaped!(widget.model);
              Log.d("=== 进入当前设备详情 === 具体值是 ${widget.model.productId}");
            }
          }
        });
  }

  Widget nextDeviceWidget() {
    return FuncUtils.isListEmpty(widget.model.childDeviceList)
        ? Gaps.empty
        : GestureDetector(
            onTap: () => NavigateUtils.toChildDevices(
              widget.model,
              widget.model.deviceId!,
            ),
            child: Container(
              height: 50,
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                  border: Border(top: BorderSide(color: Colour.dividerColor))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    ResKey.childDevice.tr,
                    style: TextStyle(
                        color: Colour.primaryColor,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500),
                  ),
                  const Icon(
                    Icons.chevron_right,
                    color: Colour.hintTextColor,
                  )
                ],
              ),
            ),
          );
  }

  Widget statusWidget(ConnectStatusType? statusType) {
    Color color;
    switch (statusType) {
      case ConnectStatusType.on:
        color = const Color(0xFF00AE66);
        break;

      default:
        color = Colour.labelTextColor;
        break;
    }
    return Opacity(
      opacity: statusType == null ? 0 : 1,
      child: BrnTagCustom(
        tagText: statusType?.label ?? '',
        textColor: color,
        backgroundColor: color.withOpacity(0.1),
        fontSize: 12.sp,
        textPadding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2),
      ),
    );
  }

  subscribeConnectStatus() {
    var stream = useSubsribe.start([widget.model.deviceId!], true,
        type: MessageEventType.networkStatus).stream;
    streamSubscription = stream.listen((data) {
      if (data['networkStatus'] != null) {
        connectStatus = $enumDecodeNullable(
            $ConnectStatusTypeEnumMap, data['networkStatus'],
            unknownValue: ConnectStatusType.unConfig);
        if (mounted) {
          setState(() {});
        }
      }
    });
  }

  Future disposeSubscribeConnectStatus() async {
    useSubsribe.start([widget.model.deviceId!], false,
        type: MessageEventType.networkStatus);
    await streamSubscription?.cancel();
    await useSubsribe.closeListen();
  }
}
